﻿#include "commandserver.h"
#include "mainwindowh.h"

CommandServer::CommandServer(quint16 port, QObject *parent)
	: m_port(port), QObject(parent), m_server(new QTcpServer(this))
{
}

CommandServer::~CommandServer()
{
}
void CommandServer::SetProcessor(MainWindowh* handle)
{
	m_process = handle;
}


void CommandServer::start() 
{
	if (!m_server->listen(QHostAddress::Any, m_port)) {
		emit errorOccurred("Command service failed to start: " + m_server->errorString());
		return ;
	}

	emit serviceStarted("Command service running on port " + QString::number(m_port));
	return ;
}

void CommandServer::stop() {
	m_server->close();
	emit serviceStopped("Command service stopped");
}

void CommandServer::handleNewConnection() 
{
	while (m_server->hasPendingConnections()) {
		QTcpSocket* client = m_server->nextPendingConnection();
		connect(client, &QTcpSocket::readyRead, this, [this, client]() {
			processClientData(client);
			});
		connect(client, &QTcpSocket::disconnected, this, [client]() {
			client->deleteLater();
			});
	}
}

void CommandServer::processClientData(QTcpSocket* client)
{
	while (client->canReadLine()) {
		QByteArray data = client->readLine().trimmed();
		QByteArray ans = "0000\n";
		if (m_process) {
			ans = m_process->CommandProcessor(data);
		}

		client->write(ans);
	}
}
